package com.lwi.log.filter;


import com.intellij.execution.filters.Filter;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.project.Project;
import com.lwi.log.utils.ConfigUtil;
import com.lwi.log.utils.KeyNameUtil;
import com.lwi.log.utils.PrintlnUtil;
import com.lwi.log.utils.SqlUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * sql 过滤器
 *
 * @author Administrator
 */
public class LogFilter implements Filter {
    private final Project project;
    /**
     * 查询的SQL
     */
    private static String preparingLine = "";
    /**
     * 查询的SQL参数
     */
    private static String parametersLine = "";

    public LogFilter(Project project) {
        this.project = project;
    }

    @Nullable
    @Override
    public Result applyFilter(@NotNull String s, int i) {
        if (ObjectUtils.isNotEmpty(this.project)) {
            if (StringUtils.isNotEmpty(s)) {
                printlnLogs(s, i);
            }
        }
        return null;
    }

    /**
     * 打印日志
     *
     * @param s
     * @param i
     */
    private void printlnLogs(String s, int i) {
        final String PREPARING = ConfigUtil.getPreparing(project);
        final String PARAMETERS = ConfigUtil.getParameters(project);
        if (s.contains(PREPARING)) {
            preparingLine = s;
        }
        if (!StringUtils.isEmpty(preparingLine) && s.contains(PARAMETERS)) {
            parametersLine = s;
        }
        if (StringUtils.isNotEmpty(preparingLine) && StringUtils.isNotEmpty(parametersLine)) {
            //序号前缀字符串
            String[] restoreSql = SqlUtil.restoreSql(project, preparingLine, parametersLine);
            PrintlnUtil.println(project, KeyNameUtil.SQL_Line + restoreSql[0], ConsoleViewContentType.USER_INPUT);
            PrintlnUtil.printlnSqlType(project, restoreSql[1]);

            // 清空
            preparingLine = "";
            parametersLine = "";
        }
    }
}
